package controllers

import (
	"fmt"
	"encoding/json"
	"hapi/models"
	"time"
	// "fmt"
	"github.com/astaxie/beego"
)

// Operations about aritcles
type HitdicProjectController struct {
	beego.Controller
}

// @Title AddHitdicProject
// @Description Logs hitdicproject into the system
// @Param	body		body 	models.HitdicProject	true		"body for content of a hitdic project"
// @Success 200 {string} string
// @Failure 403 body is empty
// @router / [post]
func (u *HitdicProjectController) AddHitdicProject() {
	// fmt.Println(u.Ctx.Input.RequestBody)
	// when testing the api in swagger the content of fields, created and updated, should be deleted in order to get the correct result for json.Unmarshal.
	var pro models.HitdicProject
	fmt.Println(string(u.Ctx.Input.RequestBody))
	err := json.Unmarshal(u.Ctx.Input.RequestBody, &pro)
	fmt.Println("user-id", pro.Uid.Id)
	user, err := models.GetUser(pro.Uid.Id)
	// Check if the user exists
	if err != nil {
		// user does not exist
		u.Data["json"] = map[string]string{"token": "User do not exists"}
	} else {
		// user exist
		// Create the Hitdic project
		var p models.HitdicProject
		p.Created = time.Now()
		p.Updated = time.Now()
		p.SimInput = pro.SimInput
		p.OpInput = pro.OpInput
		p.DbInput = pro.DbInput
		p.Uid = user
		pid, err := models.AddHitdicProject(p)
		if err != nil {
			fmt.Println("error: ", err)
		}
		fmt.Println("pid", pid)
		// Create the experimental data
		
		u.Data["json"] = map[string]string{"token": "User exists"}
	}
	fmt.Println(err)
	fmt.Println(pro)
	// tokenstr := "token"
	// u.Data["json"] = map[string]string{"token": tokenstr}
	u.Ctx.ResponseWriter.Header().Add("Access-Control-Allow-Origin", "*")
	u.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	
	u.ServeJSON()
}

// @Title GetAll
// @Description get all projects
// @Success 200 {object} models.HitdicProject
// @router / [get]
func (u *HitdicProjectController) GetAll() {
	u.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	users := models.GetAllHitdicProjects()
	u.Data["json"] = users
	u.ServeJSON()
}